package com.multitrack.main;

import static com.multitrack.datatype.SocketMessage.AGREE_SUCCESS;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gcm.GCMRegistrar;
import com.multitrack.datatype.STATE;
import com.multitrack.datatype.SocketMessage;
import com.multitrack.datatype.UserInfo;
import com.multitrack.util.CloseAlertDialog;
import com.multitrack.util.CommunicationManager;
import com.multitrack.util.Progress;
import com.multitrack.util.SQLite;
import com.multitrack.util.ThreadManager;

public class JoinActivity extends Activity {

	static final String TAG = "JoinActivity";
	static final int TURE = 1;
	static final int FALSE = 0;
	public static String regId = "";
	EditText nameEdit;

	SQLite mHelper;
	Progress mProgress;

	private UserInfo info;

	private CommunicationManager joinAppThread;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.join_activity);

		nameEdit = (EditText) findViewById(R.id.name_edit);

		mHelper = new SQLite(this);

		mProgress = new Progress(this);
		mProgress.setTitle(R.string.processing);
		mProgress.setMessage(R.string.wait);
		mProgress.setCancelable(false);

		info = new UserInfo();
		Intent intent = getIntent();
		info.setAgree(intent.getBooleanExtra(AGREE_SUCCESS.name(), false));
		
		final String SENDER_ID = "633471946472";
		regId = GCMRegistrar.getRegistrationId(this);
		// 등록된 ID가 없으면 ID값을 얻어옵니다
		if (regId.equals("") || regId == null) {

			GCMRegistrar.register(JoinActivity.this, SENDER_ID);

		} else {
			Log.w(TAG, "Already Registered : " + regId);
		}
	}

	public void mOnClick(View v) {
		/*
		 * TODO: 
		 * 입력한 이름을 검사하는 함수가 필요합니다.
		 */
		if (nameEdit.getText().length() == 0) {
			new CloseAlertDialog(JoinActivity.this, R.string.notice,
					R.string.registration, null).show();
			return;
		}
		System.out.println(nameEdit.getText().length());

		String id, name;
		id = mHelper.dbGetMyId();
		name = nameEdit.getText().toString();
		mHelper.dbSetMyName(name);
		
		info.setId(id);
		info.setName(name);
		info.setGcm_id(regId);
		if(regId.equals("") || regId == null)
		{
			Toast.makeText(JoinActivity.this, "푸시 서비스 등록 중입니다. 잠시 기다려주세요.", Toast.LENGTH_SHORT).show();
			return;
		}
		Log.d("kys", regId);
		// gcmid 넣는 부분
		excuteAppJoin(info);
	}

	private void excuteAppJoin(UserInfo userInfo) {
		if (ThreadManager.isInThread(joinAppThread) == false) {
			if (mProgress.isShowing() == false) {
				mProgress.show();
			}
			joinAppThread = new CommunicationManager();
			ThreadManager.excute(joinAppThread, mHandler,
					SocketMessage.APP_JOIN, userInfo);
		}
	}

	Handler mHandler = new Handler() {

		SocketMessage resultMessage;
		STATE resultState;

		@Override
		public void handleMessage(Message msg) {

			resultState = STATE.getEnum(msg.what);
			resultMessage = (SocketMessage) msg.obj;

			if (mProgress.isShowing() == true) {
				mProgress.dismiss();
			}

			switch (resultState) {
			case SOCKET_SUCCESS:
				uponSuccess();
				break;
			case SOCKET_FAIL:
				uponFail();
				break;
			case SOCKET_EXCEPTION:
				uponException();
				break;
			}
		}

		private void uponSuccess() {

			switch (resultMessage) {
			case SQL_QUERY_SUCCESS:
				Intent intent = new Intent(getCurrentFocus().getContext(),
						TabMenuActivity.class);
				intent.putExtra(STATE.MESSAGE, resultState);
				startActivity(intent);
				finish();
				break;

			case SQL_QUERY_ERROR:
				break;
			}

		}

		private void uponFail() {
			OnClickListener listener = new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					Intent intent = new Intent(getCurrentFocus().getContext(),
							TabMenuActivity.class);
					intent.putExtra(STATE.MESSAGE, resultState);
					startActivity(intent);
					finish();
				}
			};

			// String message = "서버 접속에 실패하였습니니다.\nEvent가 비 활성화 됩니다.";
			new CloseAlertDialog(getCurrentFocus().getContext(),
					R.string.notice, R.string.fail_connect_server
							+ R.string.inactive_event, listener).show();

		}

		private void uponException() {
			OnClickListener nListener = new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {

					excuteAppJoin(info);
					finish();
				}
			};

			OnClickListener pListener = new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					uponFail();
				}
			};

//			String message = "다시 연결하시겠습니까?\n(R.string)";
			new CloseAlertDialog(getCurrentFocus().getContext(),
					R.string.notice, R.string.reconnect, nListener, pListener).show();

		}
	};

}